package com.demo.common.controller;

import java.util.Date;
import java.util.Optional;

import com.demo.common.model.Blog;
import com.jfinal.core.Controller;

public class BlogController extends Controller {

	public void index() {
		setAttr("blogs", Blog.me.find("select * from Blog"));
		System.out.println("执行index");
		render("index.jsp");
	}

	public void form() {
		Integer id = getParaToInt("id", 0);
		if (id > 0) {
			setAttr("blog", Blog.me.findById(id));
		}
		render("form.jsp");
	}

	public void save() {
		getFile();
		Blog blog = getModel(Blog.class);
		if (Optional.ofNullable(blog.getInt("id")).orElse(0).intValue() > 0) {
			blog.update();
		} else {
			blog.set("publishTime", new Date());
			blog.save();
		}
		index();
	}

	public void delete() {
		Optional<Integer> optional = Optional.of(getParaToInt("id"));
		if (optional.isPresent() && optional.get() > 0)
			if (Blog.me.deleteById(optional.get())) {
				index();
				return;
			}
		renderText("删除失败！");
	}

}
